var Server = function(options) {
	this.host = options.host;
	this.port = options.port;
	this.username = options.username;
	this.password = options.password;
	this.name = options.name;
	this.tasks = options.tasks;

	this.connected =false;

	this.conn = function(callback) {
		var Client = require('ssh2').Client;
		var client = new Client();
		var that = this;
		client.on('ready', function() {
			that.connect = client;
			that.connected = true;
			callback();
		}).connect({
			host: this.host,
			port: this.port,
			username: this.username,
			password: this.password
		});
	};
	this.disconn = function(){
		this.connect.end();
		this.connected = false;
	};

	this.uploadFile = function(local, file, remote, callback){
		if(this.connected){
			var fs = require('fs');
			var that = this;
			this.connect.sftp(function(err, sftp){
				if(err){
					console.log( "Error, problem starting SFTP: %s", err );
				}

				var remotePath =remote +  file.substring(0, file.lastIndexOf("/"));
				console.log(remotePath);

				that.connect.exec('mkdir -p ' + remotePath, function(){
					console.log( "SFTP started : " + local + file);
					var readStream = fs.createReadStream( local + file );

					var writeStream = sftp.createWriteStream( remote + file );
					writeStream.on('end', function(){
						console.log('writeStream end.');
					});
					writeStream.on('close',function(){
						console.log('writeStream close.');
						sftp.end();
						callback();
					});
					readStream.pipe( writeStream );
				});

				
			});
		}else{
			$.messager.alert('系统消息', '请先连接远程服务器','info');
		}
	};


	this.getConf = function() {
		return {
			host: this.host,
			port: this.port,
			username: this.username,
			password: this.password,
			name: this.name,
			tasks: this.tasks
		};
	};
	this.addTask = function(t){
		this.tasks.push(t);
		servers.persist();
	};

}

var servers = (function() {
	return {
		servers: {},
		createServer: function() {
			$('#server-create').dialog({
				title: "创建链接",
				width: 400,
				height: 280,
				modal: true,
				closed: false,
				buttons: [{
					text: '保存',
					handler: servers.saveServer
				}, {
					text: '取消',
					handler: function() {
						$('#server-create').dialog('close');
					}
				}]
			});
		},
		addServer: function(s, f) {
			if (servers.servers[s.name]) {
				return false;
			}
			var server = new Server(s);
			servers.servers[s.name] = server;
			var url = 'server.html?id=' + s.name;
			var content = '<iframe frameborder="0" scrolling="no" src="' + url
                    + '" style="width:100%;height:100%;"></iframe>';
			$("#server-tabs").tabs('add', {
				title: s.name,
				content: content,
				id: s.name 
			});
			if (f) {
				servers.persist();
			}
			return true;
		},
		getServer: function(name) {
			var server =  servers.servers[name];
			if(!server){
				var fs = require('fs');
				var cfgs = fs.readFileSync('conf.json');
				var serverList = JSON.parse(cfgs);
				for(var s in serverList){
					var _s = serverList[s];
					if(_s.name == name){
						server = new Server(s);
						break;
					}
				}
			}
			return server;
		},
		persist: function() {
			var fs = require('fs');
			var cfgs = [];
			for (var i in servers.servers) {
				var server = servers.servers[i];
				cfgs.push(server.getConf());
			};
			fs.writeFile('conf.json', JSON.stringify(cfgs), function(err) {});
		},
		readCfg: function() {
			var fs = require('fs');
			var cfgs = fs.readFileSync('conf.json');
			var serverList = JSON.parse(cfgs);
			for (var s in serverList) {
				servers.addServer(serverList[s]);
			}
		},
		saveServer: function() {
			var s = {};
			$("#server-create").find('input').each(function() {
				if ($(this).attr('name')) {
					s[$(this).attr('name')] = $(this).val();
				}
			});
			s.tasks = [];
			if (!servers.addServer(s, true)) {
				$.messager.alert('系统提示', '服务器名称已存在', 'info');
				return false;
			}
			$("#server-create").dialog('close');
		},
		openConn: function(id) {
			var server = servers.getServer(id);
			$.messager.progress({
				msg: '连接中...'
			});
			server.conn(function() {
				$.messager.progress('close');
				$(node.target).css('color', 'red');
			});
		}
	};
})();